﻿
var blog_username = getUserName();


function getUserName() {
    var aburl = location.href.replace('http://', '');
    var url = aburl.substr(location.host.length + 1);
    var prms = url.split('/');
    var uname;
    for (var i = 0; i < prms.length; i++) {
        if ($.trim(prms[i])) {
            uname = prms[i];
            break;
        }
    }
    return "/" + uname + "/";
}

function showAjaxResult(obj, htmObj, warn) {
    if (obj.State == 1) {
        if (warn != null) {
            layerAlert(warn);
        } else {
            location.href = obj.Url;
        }
    } else if (obj.State == 2) {
        if (htmObj != null) {
            htmObj.html(obj.Message);
        } else {
            window.location = obj.Url;
        }
    } else if (obj.State == 3) {
        if (warn != null) {
            layerAlert(warn);
        } else {
            location.href = obj.Url;
        }
    } else {
        htmObj.html(obj.Message);
    }
}
$.extend({
    showAjaxMessage: function (data, htmlObj, warn) {
        showAjaxResult(data, htmlObj, warn);
    },
    fillNumString: function (num) {
        if (num < 10) {
            num = "0" + num;
        }
        return num;
    },
    /*1.用浏览器内部转换器实现html转码*/
    htmlEncode: function (html) {
        if (!$.trim(html)) {
            return '';
        }
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(html));
        return div.innerHTML;
    },
    /*2.用浏览器内部转换器实现html解码*/
    htmlDecode: function (text) {
        if (!$.trim(text)) {
            return '';
        }
        //1.首先动态创建一个容器标签元素，如DIV
        var temp = document.createElement("div");
        //2.然后将要转换的字符串设置为这个元素的innerHTML(ie，火狐，google都支持)
        temp.innerHTML = text;
        //3.最后返回这个元素的innerText(ie支持)或者textContent(火狐，google支持)，即得到经过HTML解码的字符串了。
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    }

});

var UeditorFontSizeArray = [10, 11, 12, 14, 16, 18, 20];

function setInputFilter() {
    var elems = $('.inputFilter').filter("input[type=text]");
    if (elems.length > 0) {
        $(elems).each(function (n) {
            $(this).on({
                keyup: function () {
                    if (/["'<>%;)(&+]/.test($(this).val())) {
                        $(this).val($(this).val().replace(/["'<>%;)(&+]/, ""));
                    }
                },
                keypress: function () {
                    if (/["'<>%;)(&+]/.test($(this).val())) {
                        $(this).val($(this).val().replace(/["'<>%;)(&+]/, ""));
                    }
                }
            });
        })
    }
}

function isPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

//获取文档内容实际高度
function getScrollHeight() {
    return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}

function getScroll() {
    var bodyTop = 0;
    if (typeof window.pageYOffset != 'undefined') {
        bodyTop = window.pageYOffset;
    } else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
        bodyTop = document.documentElement.scrollTop;
    }
    else if (typeof document.body != 'undefined') {
        bodyTop = document.body.scrollTop;
    }
    return bodyTop
}

layer.config({
    skin: 'layui-layer-molv'
});

var layerAlert = function (msg, ok) {
    var index = layer.alert(msg, { title: "提示" }, function () {
        if (ok != null && ok != undefined) {
            ok();
        }
        layer.close(index);
    });
}

var layerTips = function (msg, id) {
    layer.tips(msg, '#' + id, { tips: [1, '#3595CC'], time: 3000 });
}
var layerTips2 = function (msg, id) {
    layer.tips(msg, '#' + id, { time: 3000 });
}

var layerMsg = function (msg, fun, icon, time) {
    layer.msg(msg, { icon: icon == null ? 1 : icon, time: time == null ? 2000 : time }, function () {
        doUeParse();
        if (fun != null && fun != undefined) {
            fun();
        }
    });
}
var layerPrompt = function (title, v, ok) {
    var index = layer.prompt({
        formType: 2,
        value: v,
        title: title
    }, function (value, index, elem) {
        if (ok != undefined) {
            ok();
        }
        layer.close(index);
    });
}


var layerOpen = function (title, html, width, height, success) {
    width = width || 450;
    height = height || 350;
    var index = layer.open({
        type: 1,
        title: title,
        shadeClose: false,
        shade: [0.5, '#393D49'],
        maxmin: false, //开启最大化最小化按钮
        //area: [`${width}px`, `${height}px`],
        area: [width + "px", height + "px"],
        content: html,
        zIndex: 991,
        success: function (html, id) {
            if (success != null && success != undefined) {
                success(id);
            }
        }
    });
}

var openIframe = function (url, title, width, height, success) {
    width = width || 450;
    height = height || 350;
    var index = layer.open({
        type: 2,
        title: title,
        shadeClose: false,
        shade: [0.5, '#393D49'],
        maxmin: false, //开启最大化最小化按钮
        //area: [`${width}px`, `${height}px`],
        area: [width + "px", height + "px"],
        content: url,
        zIndex: 991,
        success: function (html, id) {
            if (success != null && success != undefined) {
                success();
            }
        }
    });
}

var loginHtml = "<div class=\"loginfrm2\">" +
                "<div class=\"block\">" +
                    "<label class=\"lbl\">用户名</label><br>" +
                    "<input name=\"Account\" class=\"inputbox inputFilter\" id=\"Account\" type=\"text\"  placeholder = \"请输入用户名\" maxlength=\"20\" value=\"1111\">" +
                    "<span class=\"red\">*</span>" +
                "</div>" +
                "<div class=\"block\">" +
                    "<label class=\"lbl\">密码</label><br>" +
                    "<input name=\"Password\" class=\"inputbox\" id=\"Password\" type=\"password\"  placeholder = \"请输入密码\" maxlength=\"250\" >" +
                    "<span class=\"red\">*</span>" +
                "</div>" +
                "<div class=\"block\"><input name=\"isRemember\" id=\"chkRemember\" type=\"checkbox\" checked=\"checked\" value=\"true\">记住密码</div>" +
                "<div class=\"block\">" +
                    "<input class=\"login-btn\" type=\"button\" id=\"layer-login\" value=\"立即登录\">&nbsp;<span class=\"red\" id=\"loginErr\"></span>" +
                "</div>" +
                "<div style=\"line-height: 1.8;\">" +
                    "<span><i class=\"icon-double-angle-right\"></i> <a title=\"进入小博客首页\" href=\"/home/index\">小博客首页</a></span><br>" +
                    "<span><i class=\"icon-double-angle-right\"></i> <a title=\"注册成为我们的一员\" href=\"/account/register\">没有帐号？立即注册</a></span><br>" +
                    "<span><i class=\"icon-double-angle-right\"></i> <a title=\"用您的注册邮箱找回您的密码\" href=\"/account/findpwd\">忘记密码？</a></span><br>" +
                    "<span><i class=\"icon-double-angle-right\"></i> <a title=\"将您的建议或者您发现的问题反馈给我们\" href=\"/system/buglist\">我要提Bug</a></span>" +
                "</div>" +
      "</div><div class=\"custo-login2\">  <div style=\"margin-bottom:10px;\">使用第三方帐号直接登录</div><a href=\"javascript:;\" id=\"qq-login2\" title=\"QQ帐号登录\"><img src=\"/Content/Images/QQ-login2.png\" /></a>&nbsp;" +
      "<a href=\"javascript:;\" id=\"wb-login\" title=\"新浪微博帐号登录\"><img src=\"/Content/Images/wb-login.png\" /></a></div>";

var layerCheckLogin = function (isRefresh) {
    var islogin = false;
    $.ajax({
        async: false,
        type: "post",
        dataType: "json",
        url: '/account/CheckIsLogin',
        success: function (o) {
            if (o.IsLogin) {
                islogin = true;
            } else {
                openLoginView(isRefresh);
            }
        }
    });
    return islogin;
}

function refreshUserView() {
    $('#nav-login-head').load('/home/_bloghead', function (html) {
        $(this).html(html);
    })
}
function openLoginView(isRefresh) {
    var loop;
    var view = layer.open({
        type: 1,
        title: '登录小博客',
        shadeClose: false,
        shade: [0.5, '#393D49'],
        maxmin: false, //开启最大化最小化按钮
        area: ['450px', '445px'],
        content: loginHtml,
        success: function () {
            $('#qq-login2').attr("onclick", "return window.open('https://graph.qq.com/oauth2.0/authorize?client_id=101333775&redirect_uri=" + encodeURI("http://www.xiaoboke.net/qc_back.html") + "&response_type=code&display=default&state=qq', 'newWindow', 'height=400, width=600, top=100, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')");
            $('#wb-login').attr("onclick", "return window.open('https://api.weibo.com/oauth2/authorize?client_id=1491702255&redirect_uri=" + encodeURI("http://www.xiaoboke.net/qc_back.html") + "&response_type=code&display=default&state=wb', 'newWindow', 'height=400, width=600, top=100, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')");
            setInputFilter();
            if ($.cookie("xiaoboke-uname") != undefined && $.cookie("xiaoboke-uname") != null) {
                $("#Account").val($.cookie("xiaoboke-uname"));
                $("#Password").val($.cookie("xiaoboke-pwd"));
            }
            $("#Account").focus();
            $('#layer-login').on("click", function () {
                var ok = true;
                if (!$.trim($('#Account').val())) {
                    $('#Account').next('span').text('*请输入用户名');
                    $("#Account").focus();
                    return;
                }
                if ($.trim($('#Account').val()).length < 4 || !/^[A-Za-z0-9]{4,20}$/.test($.trim($('#Account').val()))) {
                    $('#Account').next('span').text('*用户名为4-20位字母或数字');
                    $("#Account").focus();
                    return;
                }
                $('#Account').next('span').text('*');
                if (!$.trim($('#Password').val())) {
                    $('#Password').next('span').text('*请输入密码');
                    $("#Password").focus();
                    return;
                }
                if ($.trim($('#Password').val()).length < 6) {
                    $('#Password').next('span').text('*密码长度不对');
                    $("#Password").focus();
                    return;
                }
                $('#Password').next('span').text('*');
                var isRemember = $('#chkRemember').attr("checked") == "checked" ? true : false;
                $.post('/account/login', { account: $('#Account').val(), password: $('#Password').val(), isRemember: isRemember }, function (o) {
                    if (o.State == 1) {
                        layer.close(view);
                        layerMsg("登录成功，即将刷新页面……", function () {
                            if (isRemember) {
                                //$.cookie(‘cookieName’,'cookieValue’，｛expires：7，path：’/'，domain: ‘aaa.com’，secure: false，raw:false｝);
                                //注：domain：创建cookie所在网页所拥有的域名；secure：默认是false，如果为true，cookie的传输协议需为https；
                                //raw：默认为false，读取和写入时候自动进行编码和解码（使用encodeURIComponent编码，使用decodeURIComponent解码），关闭这个功能，请设置为true。
                                $.cookie("xiaoboke-uname", $("#Account").val(), { expires: 7, path: "/" });
                                $.cookie("xiaoboke-pwd", $("#Password").val(), { expires: 7, path: "/" });
                            } else {
                                $.cookie("xiaoboke-uname", null, { expires: -1, path: "/" });
                                $.cookie("xiaoboke-pwd", null, { expires: -1, path: "/" });
                            }
                            if (isRefresh != undefined && isRefresh != null && isRefresh) {
                                window.location.reload();//考虑局部刷新
                            } else {
                                refreshUserView();//局部刷新
                            }
                        }, null, null, 1000);
                    } else {
                        $.showAjaxMessage(o, $("#loginErr"), null);
                    }
                })
            })
        },
        end: function () {
            clearInterval(loop);
        }
    });
    return false;
}

var layerConfirm = function (msg, ok, no) {
    var index = layer.confirm(msg, {
        title: '提示',
        icon: 3,
        btn: ['确定', '不要'] //按钮
    }, function () {
        ok();
        layer.close(index);
    }, function () {
        if (no != null && no != undefined) {
            no();
        }
    });
}

function mvcPagerComplete(data) {
    doUeParse();
    $(window).scrollTop(0);
}

var doUeParse = function () {
    var ucontent = $('.ueditorContent');
    if (ucontent != null && ucontent != undefined && ucontent.length > 0) {
        uParse('.ueditorContent', {
            rootPath: '/Content/ueditor/',
            liiconpath: '/Content/ueditor/themes/ueditor-list/'
        });
    }
}

function agreeSys(a, count, type) {
    $.post('/system/agreesys', { type: type }, function (o) {
        if (o.State == 1) {
            layerMsg("给力！^_^");
            $(a).html('<i class="icon-heart-empty"></i> 赞(<label class="' + (type == 1 ? 'spfloor' : 'lbnum') + '">' + (++count) + '</label>)');
        } else {
            layerAlert(o.Message);
        }
    }, "json");
}

function doAgree(url, id, count, a) {
    if (!layerCheckLogin(true)) {
        return;
    }
    $.post(url, { id: id }, function (o) {
        if (o.State == 1) {
            layerMsg("给力！^_^");
            $(a).html('<i class="icon-heart"></i> 赞(' + (++count) + ')');
        } else {
            layerAlert(o.Message);
        }
    }, "json");
}


$(function () {
    //$(".datePicker").datepicker({
    //    numberOfMonths: 1,//显示几个月  
    //    showButtonPanel: true,//是否显示按钮面板  
    //    dateFormat: 'yy-mm-dd',//日期格式  
    //    prevText: '<上月',
    //    nextText: '下月>',
    //    currentText: '今天',
    //    clearText: "清除",//清除日期的按钮名称  
    //    closeText: "关闭",//关闭选择框的按钮名称  
    //    yearSuffix: '年', //年的后缀  
    //    showMonthAfterYear: true,//是否把月放在年的后面  
    //    //defaultDate: '2011-03-10',//默认日期  
    //    //minDate: '2011-03-05',//最小日期  
    //    //maxDate: '2011-03-20',//最大日期  
    //    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    //    dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    //    dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
    //    dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
    //    beforeShow: function (a, b) {

    //    }
    //});
    doUeParse();
    setInputFilter();
    $(window).scroll(function () {
        if ($(window).scrollTop() >= 500) { //向下滚动像素大于这个值时触发
            $('.actGotop').fadeIn(300); //淡入的时间，越小出现的越快~
        } else {
            $('.actGotop').fadeOut(300); //淡出的时间，越小消失的越快~
        }
        if ($(window).scrollTop() >= $(document).height() - $(window).height()) {
            $('.gobottom').hide();
        } else {
            $('.gobottom').show();
        }
    });
    $('.gotop').click(function () {
        $('html,body').animate({ scrollTop: 0 }, 300);
    });
    $('.gobottom').click(function () {
        $('html,body').animate({ scrollTop: $(document).height() }, 300);
    });

})
